#include "widget.h"
#include "ui_widget.h"
#include<QPixmap>
#include<QDir>
#include<QDebug>
#include<QList>
#include<btform.h>
#include<QJsonObject>
#include<QFileDialog>
#include<QDir>
#include"commonpage.h"
#include<QMediaPlaylist>
#include<QString>
#include<QMessageBox>
#include<QSqlError>
#include<QSqlQuery>
#include<QSystemTrayIcon>
#include<QMenu>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    initUi();
    initSQLite();
    initMusicList();
    connectSignalAndSlots();

}

Widget::~Widget()
{
    delete ui;
}

void Widget::initUi()
{


    this->setWindowFlags(Qt::WindowType::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowIcon(QIcon(":/images/tubiao.png"));
    ui->max->setEnabled(false);
   QGraphicsDropShadowEffect* shadoweffect=new QGraphicsDropShadowEffect(this);
   shadoweffect->setOffset(0,0);
   shadoweffect->setColor("#000000");
   shadoweffect->setBlurRadius(5);
   this->setGraphicsEffect(shadoweffect);

   QSystemTrayIcon* trayIcon=new QSystemTrayIcon(this);
   trayIcon->setIcon(QIcon(":/images/tubiao.png"));
   QMenu* trayMenu=new QMenu(this);
   trayMenu->addAction("还原",this,&QWidget::showNormal);
   trayMenu->addSeparator();
   trayMenu->addAction("退出",this,&Widget::quitQQMusic);
   trayIcon->setContextMenu(trayMenu);
   trayIcon->show();

   QPixmap pixmap(":/images/Logo.png");
   if (!pixmap.isNull()) {
       // 设置pixmap比例
       pixmap = pixmap.scaled(ui->logo->size());
       // 将pixmap设置到label
       ui->logo->setPixmap(pixmap);
   } else {
       qDebug() << "Failed to load logo image from resource.";
   }

   //设置我喜欢，本地音乐，最近播放页面

   ui->likePage->setMusicListType(PageType::LIKE_PAGE);
    ui->localPage->setMusicListType(PageType::LOCAL_PAGE);
    ui->recentPage->setMusicListType(PageType::HISTORY_PAGE);

   ui->likePage->setCommonPageUI("我喜欢",":/images/like.png");
   qDebug()<<ui->likePage->pagetype;



   ui->localPage->setCommonPageUI("本地音乐",":/images/local.png");
    qDebug()<<ui->localPage->pagetype;

   ui->recentPage->setCommonPageUI("最近播放",":/images/recent.png");
    qDebug()<<ui->recentPage->pagetype;


   //初始化6个btform
   ui->Rec->seticon(":/images/rec.png", "推荐", 1);
   ui->audio->seticon(":/images/radio.png", "电台",2);
    ui->music->seticon(":/images/music.png", "⾳乐馆", 3);
   ui->like->seticon(":/images/like.png", "我喜欢",4);
   ui->local->seticon(":/images/local.png", "本地下载", 5);
   ui->recent->seticon(":/images/recent.png", "最近播放", 6);


   //bt控件和stackwidget的page建立映射
   QList<btForm*> btlist=this->findChildren<btForm*>();

   int size=btlist.size();
   qDebug()<<"btlist:"<<size;
   bts.reserve(size);

   for( auto& e:btlist)
   {
       bts.push_back(e);
   }
    qDebug()<<"bts:"<<size;

    //推荐页面的初始化
    srand(time(NULL));
    ui->recMusicBox->initRecBoxUi(RandomPicture(),1);
    ui->supplyMusicBox->initRecBoxUi(RandomPicture(),2);

    //隐藏动画
   QList<btForm*> btforms=this->findChildren<btForm*>();
   for(auto& e:btforms)
   {
       if(e->objectName()!="local")
       {
          e->hideanimal();

       }else
       {
           //设置本地默认动画和stackwiget页面
           ui->stackedWidget->setCurrentIndex(0);
       }
   }

   ui->play->setIcon(QIcon(":/images/play_2.png"));
   ui->playmode->setIcon(QIcon(":/images/shuffle_2.png"));
   volumeTool=new VolumeTool(this);
   //初始话音乐媒体对象
     initPlayer();
   //界面设置为localpage
   ui->stackedWidget->setCurrentIndex(4);
   curPage=ui->localPage;
   ui->local->showanimal();
   //歌词显示页面隐藏
   lrcpage=new LrcPage(this);
  lrcpage->setGeometry(10,10,lrcpage->width()-3,lrcpage->height());
  lrcpage->hide();
   lrcAnimation = new QPropertyAnimation(lrcpage, "geometry", this);
   lrcAnimation->setDuration(250);
   lrcAnimation->setStartValue(QRect(9, 10+lrcpage->height(),lrcpage->width(), lrcpage->height()));
   lrcAnimation->setEndValue(QRect(9, 10, lrcpage->width(), lrcpage->height()));

}


void Widget::connectSignalAndSlots()
{
   connect(ui->min,&QPushButton::clicked,this,&Widget::on_min_clicked);

    //进行绑定
    connect(ui->Rec,&btForm::btsignal,this,&Widget::onBtFormClick);
    connect(ui->audio,&btForm::btsignal,this,&Widget::onBtFormClick);
    connect(ui->local,&btForm::btsignal,this,&Widget::onBtFormClick);
    connect(ui->like,&btForm::btsignal,this,&Widget::onBtFormClick);
    connect(ui->recent,&btForm::btsignal,this,&Widget::onBtFormClick);
    connect(ui->music,&btForm::btsignal,this,&Widget::onBtFormClick);
    //音乐更新
    connect(ui->likePage, &CommonPage::updateLikeMusic, this,
    &Widget::onUpdateLikeMusic);
    connect(ui->localPage, &CommonPage::updateLikeMusic, this,
    &Widget::onUpdateLikeMusic);
    connect(ui->recentPage, &CommonPage::updateLikeMusic, this,
    &Widget::onUpdateLikeMusic);


   connect(ui->palyup, &QPushButton::clicked, this,&Widget::onPlayUpCliked);
    connect(ui->playdown, &QPushButton::clicked, this,&Widget::onPlayDownCliked);

    //播放和暂停测试歌曲
     // connect(ui->play,&QPushButton::clicked,this,&Widget::onPlayMusic);

    //播放控制信号和槽
 connect(ui->play,&QPushButton::clicked,this,&Widget::onPlayCliked);

  //每个页面的全部播放信号和槽
  connect(ui->likePage,&CommonPage::playAll,this,&Widget::onPlayAll);
  connect(ui->localPage,&CommonPage::playAll,this,&Widget::onPlayAll);
  connect(ui->recentPage,&CommonPage::playAll,this,&Widget::onPlayAll);


  //不同页面的被点击歌曲
  connect(ui->likePage,&CommonPage::playMusicByIndex,this,&Widget::playAllOfCommonPage);
 connect(ui->localPage,&CommonPage::playMusicByIndex,this,&Widget::playAllOfCommonPage);
 connect(ui->recentPage,&CommonPage::playMusicByIndex,this,&Widget::playAllOfCommonPage);
//音量设置
 connect(volumeTool,&VolumeTool::setMusicVolume,this,&Widget::setMusicSilence);

 connect(volumeTool,&VolumeTool::setSilence,this,&Widget::MusicSilence);
 //进度条播放
 connect(ui->processbar, &musicslider::setMusicSliderPosition, this,&Widget::onMusicSliderChanged);
 //歌曲封面等同步
 connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&Widget::onMetaDataAvailableChangedChanged);

 //歌词点击按钮
 connect(ui->lrcword,&QPushButton::clicked,this,&Widget::onLrcWordCliced);
}

void Widget::onBtFormClick(int id)
{
    //设置
    isDrag=false;
    //根据映射关系设置bt页面
    ui->stackedWidget->setCurrentIndex(bts[id-1]->getid()-1);
    int currentpage;
    currentpage=ui->stackedWidget->currentIndex();
    qDebug()<<currentpage;
    //点击后显示动画,隐藏其他页面的动画同时恢复样式
    bts[id-1]->showanimal();
    QList<btForm*> btlist=this->findChildren<btForm*>();
    for(auto& e:btlist)
    {
        if(e->getid()!=id)
        {
           e->hideanimal();
          e->clearbg();
        }

    }  

}

QJsonArray Widget::RandomPicture()
{
    QVector<QString> vecimagename;
    vecimagename<<"001.png"<<"003.png"<<"004.png"<<"005.png"<<"006.png"
               <<"007.png"
               <<"008.png"<<"009.png"<<"010.png"<<"011.png"<<"012.png"
               <<"013.png"
               <<"014.png"<<"015.png"<<"016.png"<<"017.png"<<"018.png"
               <<"019.png"
               <<"020.png"<<"021.png"<<"022.png"<<"023.png"<<"024.png"
               <<"025.png"
               <<"026.png"<<"027.png"<<"028.png"<<"029.png"<<"030.png"
               <<"031.png"
               <<"032.png"<<"033.png"<<"034.png"<<"035.png"<<"036.png"
               <<"037.png"
               <<"038.png"<<"039.png"<<"040.png";
    std::random_shuffle(vecimagename.begin(),vecimagename.end());
    QJsonArray arry;
    for(int i=0;i<vecimagename.size();++i)
    {
        QJsonObject obj;
        obj.insert("path",":/images/rec/"+vecimagename[i]);
        //qDebug()<<i;
        QString strText = QString("推荐-%1").arg(i, 3, 10, QChar('0'));
       // qDebug()<<strText;
        obj.insert("text", strText);
        arry.append(obj);
    }
    return arry;
}

void Widget::initPlayer()
{
    player=new QMediaPlayer(this);
    playList=new QMediaPlaylist(this);

    playList->setPlaybackMode(QMediaPlaylist::Loop);
    player->setPlaylist(playList);
    player->setVolume(20);


    //播放按钮

   connect(player, &QMediaPlayer::stateChanged, this,&Widget::onPlayStateChange);
  connect(ui->playmode, &QPushButton::clicked, this,&Widget::onPlaybackModeCliked);
  connect(playList, &QMediaPlaylist::playbackModeChanged, this,&Widget::onPlaybackModeChanged);
  connect(playList,&QMediaPlaylist::currentIndexChanged,this,&Widget::onCurrentIndexChange);
  //歌曲总时间更新
  connect(player,&QMediaPlayer::durationChanged,this,&Widget::onDurationChanged);
  //歌曲播放实时时间
  connect(player, &QMediaPlayer::positionChanged, this,&Widget::positionChanged);

}

void Widget::onPlayCliked()
{
    qDebug()<<"play cliked";
    if(player->state()==QMediaPlayer::PlayingState)
    {
        player->pause();
        ui->play->setIcon(QIcon(":/images/play_2.png"));

        qDebug()<<"state : "<<player->state();

    }else if(player->state()==QMediaPlayer::PausedState)
    {
        player->play();
        ui->play->setIcon(QIcon(":/images/play_on.png"));
        if(playList->mediaCount()==0)
        playAllOfCommonPage(curPage,0);
         qDebug()<<"state : "<<player->state();
    }else if(player->state()==QMediaPlayer::StoppedState)
    {
        player->play();
        if(playList->mediaCount()==0)
        playAllOfCommonPage(curPage,0);
         qDebug()<<"state : "<<player->state();
    }



}

void Widget::onPlayStateChange()
{

    qDebug()<<"播放状态改变";
    if(player->state()==QMediaPlayer::PlayingState)
    {
        ui->play->setIcon(QIcon(":/images/play_on.png"));
    }else
    {
        ui->play->setIcon(QIcon(":/images/play3.png"));

    }
}

void Widget::onPlayUpCliked()
{
  playList->previous();

}

void Widget::onPlayDownCliked()
{
    playList->next();

}

void Widget::onPlaybackModeCliked()
{

    if(playList->playbackMode()==QMediaPlaylist::Loop)
    {
        ui->playmode->setToolTip("随机播放");
        playList->setPlaybackMode(QMediaPlaylist::Random);
    }else if(playList->playbackMode() == QMediaPlaylist::Random)
    {
    // 随机播放
    ui->playmode->setToolTip("单曲循环");
    playList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }
    else if(playList->playbackMode() == QMediaPlaylist::CurrentItemInLoop)
    {
    ui->playmode->setToolTip("列表循环");
    playList->setPlaybackMode(QMediaPlaylist::Loop);
    }
    else
    {
    qDebug()<<"播放模式错误";
    }

}

void Widget::onPlaybackModeChanged(QMediaPlaylist::PlaybackMode playbackMode)
{

    if(playbackMode == QMediaPlaylist::Loop)
    {
    ui->playmode->setIcon(QIcon(":/images/list_play.png"));
    }
    else if(playbackMode == QMediaPlaylist::Random)
    {
    ui->playmode->setIcon(QIcon(":/images/shuffle_2.png"));
    }
    else if(playbackMode == QMediaPlaylist::CurrentItemInLoop)
    {
    ui->playmode->setIcon(QIcon(":/images/single_play.png"));
    }
    else
    {
    qDebug()<<"暂不⽀持该模式";
    }

}

void Widget::onPlayAll(PageType pagetype)
{
    qDebug()<<"playALL clicked............";
   //CommonPage* page=nullptr;

    switch(pagetype)
    {
    case PageType::LIKE_PAGE:
      {
          curPage=ui->likePage;
          break;

       }
     case PageType::LOCAL_PAGE:
    {
        curPage=ui->localPage;
        break;
    }
    case PageType::HISTORY_PAGE:
    {
        curPage=ui->recentPage;
        break;
    }

    default:
        qDebug()<<"拓展";

    }
 qDebug()<<" curpage :"<<curPage;
 updateBtformAnimal();
   playAllOfCommonPage(curPage,0);

}

void Widget::playAllOfCommonPage(CommonPage *commonpage, int index)
{
     curPage=commonpage;
    updateBtformAnimal();
     qDebug()<<"curPage :"<<commonpage;
    playList->clear();
    commonpage->addMusicToPlayer(musiclist,playList);
    playList->setCurrentIndex(index);
    player->play();
    qDebug()<<"music is playing..........";

}
//播放和暂停
//void Widget::onPlayMusic()
//{

//    qDebug()<<"play music url:"<<musiclist.musicList.begin()->getMusicUrl();
//    playList->clear();
//    playList->addMedia(musiclist.musicList[0].getMusicUrl());
//    player->play();

//}

void Widget::onCurrentIndexChange(int index)
{
    curPlayMusicIndex=index;
    const QString& musicid=curPage->getMusicIdByIndex(index);
    auto it=musiclist.findMusicById(musicid);
    if(it!=musiclist.end())
    {
        it->setIsHistory(true);
    }
    ui->recentPage->reFresh(musiclist);

}

void Widget::setMusicSilence(int volum)
{
    player->setVolume(volum);

}

void Widget::MusicSilence(bool volum)
{
    player->setMuted(volum);
}

void Widget::onDurationChanged(qint64 duration)
{
    totaltime=duration;
   QString Totaltime=QString("%1:%2").arg(duration/1000/60, 2, 10,QChar('0')).arg(duration/1000%60,2,10,QChar('0'));

    ui->totalTime->setText(Totaltime);
    ui->currenttime_2->setText(Totaltime);

}

void Widget::positionChanged(qint64 duration)
{
    ui->currenttime->setText(QString("%1:%2").arg(duration/1000/60, 2, 10,
    QChar('0')) .arg(duration/1000%60,2,10,QChar('0')));
   ui->processbar->setStep((float)duration / (float)totaltime);
   if(playList->currentIndex() >= 0)
   {
       qDebug()<<"歌曲显示---------------------";
   lrcpage->showLineLrcWord(duration);
   }




}

void Widget::onMusicSliderChanged(float value)
{
    qint64 duration = (qint64)(totaltime*value);
    ui->currenttime->setText(QString("%1:%2").arg(duration/1000/60, 2, 10,
    QChar('0')).arg(duration/1000%60, 2, 10,QChar('0')));
    player->setPosition(duration);

}

void Widget::onMetaDataAvailableChangedChanged(bool available)
{
    qDebug()<<"歌曲切换";
    QString singer="未知歌手";
    QString name="未知专辑";
    if(!name.isEmpty())
    {

        auto it=musiclist.findMusicById(curPage->getMusicIdByIndex(curPlayMusicIndex));
         if(it!=musiclist.end())
         {

             name=it->getMusicName();
             singer=it->getSingerName();

         }


    }
    ui->musicname->setText(name);
    ui->musicsinger->setText(singer);


    QVariant coverImage=player->metaData("ThumbnailImage");
    if(coverImage.isValid())
    {


        QImage image=coverImage.value<QImage>();
        ui->musicCover->setPixmap(QPixmap::fromImage(image));
        ui->musicCover->setScaledContents(true);
        curPage->setImageLabel(QPixmap::fromImage(image));
    }else
    {

        qDebug()<<"此歌曲没有封面,默认设置封面";
        QPixmap pixmap=QPixmap(":/images/rec/026.png");
        ui->musicCover->setPixmap(pixmap);
        ui->musicCover->setScaledContents(true);
         curPage->setImageLabel(pixmap);

    }
    //歌词
    QString index=curPage->getMusicIdByIndex(curPlayMusicIndex);
    auto it=musiclist.findMusicById(index);
    if(it != musiclist.end())
    {
    lrcpage->parseLrc(it->getLrcFilePath());
    }



}

void Widget::onLrcWordCliced()
{
    qDebug()<<"lrcpage: show";
    lrcpage->show();
    lrcAnimation->start();

}


void Widget::on_max_clicked()
{

}

void Widget::on_min_clicked()
{
      showMinimized();
      qDebug()<<"min cliked";
}

void Widget::updateBtformAnimal()
{
    int index=ui->stackedWidget->indexOf(curPage);
    if(-1==index)
    {
        qDebug()<<"页面不存在";
        return;
    }
    QList<btForm*> btFroms=this->findChildren<btForm*>();
    for(auto e:btFroms)
    {
      if(e->getid()-1==index)
      {
         e->showanimal();
      }else
      {
         e->hideanimal();
      }


    }

}

void Widget::quitQQMusic()
{

    musiclist.writeToDB();
    sqlite.close();
    close();

}


void Widget::mousePressEvent(QMouseEvent *event)
{
    qDebug()<<"MOUSEPRESS";

    if(event->button()==Qt::LeftButton)
    {
        isDrag=true;
       //获取相对偏移量
        dragPosition=event->globalPos()-frameGeometry().topLeft();
        return;
    }
      //其他情况，执行基类的
    QWidget::mousePressEvent(event);
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
     qDebug()<<"MOUSEmove";
    if(event->buttons()==Qt::LeftButton&&isDrag)
    {
        move(event->globalPos()-dragPosition);
        return;
    }
    QWidget::mouseMoveEvent(event);
}




void Widget::on_quit_clicked()
{
   // musiclist.writeToDB();
   // sqlite.close();
   hide();
}
//音量调节
void Widget::on_volume_clicked()
{
   QPoint point=ui->volume->mapToGlobal(QPoint(0,0));
   QPoint volumeLeftTop=point-QPoint(volumeTool->width()/2,volumeTool->height());
   volumeLeftTop.setY(volumeLeftTop.y()+10);
   volumeLeftTop.setX(volumeLeftTop.x()+15);

    volumeTool->move(volumeLeftTop);
    volumeTool->show();

}
void Widget::on_addlocal_clicked()
{
    QFileDialog fileDialog(this);
    fileDialog.setWindowTitle("添加本地音乐");
   QDir dir(QDir::currentPath());
    dir.cdUp();
    qDebug()<<dir.path();
    QString projectpath=dir.path();
    projectpath+="/MiniMusic/Qtmusic";
    qDebug()<<projectpath;
    fileDialog.setDirectory(projectpath);

    QStringList mimeList;
    mimeList<<"application/octet-stream";
   fileDialog.setMimeTypeFilters(mimeList);


    fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
    fileDialog.setFileMode(QFileDialog::ExistingFiles);
    auto flage=fileDialog.exec();
    qDebug()<<"flage is :"<<flage;
    if(flage==QFileDialog::Accepted)
    {
        ui->stackedWidget->setCurrentIndex(4);

        QList<QUrl> urls=fileDialog.selectedUrls();
        qDebug()<<"select musicfile count:"<<urls.size();
       musiclist.addMusicByUrl(urls);
        ui->localPage->reFresh(musiclist);        
        ui->localPage->addMusicToPlayer(musiclist,playList);

    }


}

void Widget::onUpdateLikeMusic(bool isLike, QString musicId)
{
    qDebug()<<"onUpdateLikeMusic mudicid is :"<<musicId;
    auto it=musiclist.findMusicById(musicId);
    bool flage=it!=musiclist.end();
    if(flage)
    {
        it->setIsLike(isLike);
    }
    qDebug()<<"flage :"<<flage;
    ui->likePage->reFresh(musiclist);
    ui->localPage->reFresh(musiclist);
    ui->recentPage->reFresh(musiclist);

}

void Widget::playMusicIndex(CommonPage *page, int index)
{
   playAllOfCommonPage(page,index);
}

//数据库初始化
void Widget::initSQLite()
{
    sqlite=QSqlDatabase::addDatabase("QSQLITE");
    sqlite.setDatabaseName("MiniMusic.db");

    if(!sqlite.open())
    {
        QMessageBox::critical(this,"打开数据库失败",sqlite.lastError().text());
        return;

    }
    qDebug()<<"Sqlite连接成功，同时创建数据库MiniMusic.db!!!!";

    QString sql = ("CREATE TABLE IF NOT EXISTS MUSICS(\
                                id INTEGER PRIMARY KEY AUTOINCREMENT,\
                                musicId varchar(200) UNIQUE,\
                                musicName varchar(50),\
                                musicSinger varchar(50),\
                                albumName varchar(50),\
                                duration BIGINT,\
                                musicUrl varchar(256),\
                                isLike INTEGER,\
                                isHistory INTEGER)"
                                );
     QSqlQuery query;


      if(!query.exec(sql))
      {
          QMessageBox::critical(this,"创建数据库表失败",sqlite.lastError().text());
          return;

      }

      qDebug()<<"创建数据库表MUSICS sucess!!!!";




}

void Widget::initMusicList()
{
    musiclist.readFromDB();
   qDebug()<<"readFromDB musiclist :"<<musiclist.musicList.size();
   qDebug()<<musiclist.musicList[0].getMusicId();

    ui->likePage->setMusicListType(PageType::LIKE_PAGE);
    ui->likePage->reFresh(musiclist);
    ui->localPage->setMusicListType(PageType::LOCAL_PAGE);
   ui->localPage->reFresh(musiclist);
    ui->recentPage->setMusicListType(PageType::HISTORY_PAGE);
    ui->recentPage->reFresh(musiclist);

}
//void Widget::on_play_clicked()
//{}





void Widget::on_skin_clicked()
{
    qDebug()<<"skin ";
    QMessageBox::critical(this,"温馨提示","功能未暂未上线");
}
